<?php

namespace App\Services;

use App\Models\Sms;
use Webpatser\Uuid\Uuid;

class SmsService
{
    public $messageTxt = [
        "0" => "短信发送成功",
        "-1" => "参数不全",
        "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
        "30" => "密码错误",
        "40" => "账号不存在",
        "41" => "余额不足",
        "42" => "帐户已过期",
        "43" => "IP地址限制",
        "50" => "内容含有敏感词"
    ];
    public $smsapi  = "http://api.smsbao.com/";
    public $user    = "rose1";
    public $password = "wxw220381";
    public $content = "【海联川科】您的验证码是";

    /**
     * 发送短信验证码
     * @param $mobile
     * @return mixed|string|true
     */
    public function mobileCode($mobile){
        $code = rand(1000 ,9999);

        $currentDateTime = now();
        $fiveMinutesAgo = now()->subMinutes(5);
        $sms_num = Sms::where('mobile' ,$mobile)->where('status' ,1)->whereBetween('created_at', [$fiveMinutesAgo, $currentDateTime])->count();
        if($sms_num >= 2){
            return '发送过于频繁,请稍后再试';
        }
        $sms = new Sms();
        $sms->mobile = $mobile;
        $sms->code = $code;
        $sms->save();

        $pass = md5($this->password); //短信平台密码
        $content = $this->content.$code;//要发送的短信内容
        $sendurl = $this->smsapi."sms?u=".$this->user."&p=".$pass."&m=".$mobile."&c=".urlencode($content);
        $result = file_get_contents($sendurl);
        if($result == 0){
            //成功
            $sms->status = 1;
            $sms->done_time = date('Y-m-d H:i:s');
            $sms->save();
            return true;
        }
        return $this->messageTxt[$result];
    }

    /**
     * 验证验证码
     * @param $mobile
     * @param $code
     * @return bool
     */
    public function checkCode($mobile ,$code)
    {
        $sms = Sms::where('mobile' ,$mobile)->where('code' ,$code)->select('done_time')->orderBy('id', 'desc')->first();
        if($sms){
            if(time() - strtotime($sms->done_time) < 300){
                return true;
            }
        }
        return false;
    }

}
